import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {KeycloakService} from '../shared/services/keycloak.service';
import {Observable} from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.
    KeycloakService.getToken().subscribe();
    const defaultHeader = {ContentType: 'Application-json'};
    const authHeader = {Authorization: 'Bearer ' + KeycloakService.keycloakAuth.token};
    const headers = {
      ...defaultHeader,
      ...authHeader
    };
    // Clone the request and replace the original headers with
    // cloned headers, updated with the new defined headers.
    const authReq = req.clone({setHeaders: headers});
    return next.handle(authReq);
  }
}
